package com.lvtongka.app.fragment.my

import android.content.Intent
import android.net.Uri
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity.RESULT_OK
import androidx.lifecycle.ViewModelProvider
import com.androideasy.permissions.EasyPermissions
import com.androideasy.permissions.Permission
import com.google.zxing.client.android.MNScanManager
import com.google.zxing.client.android.model.MNScanConfig
import com.lvtongka.app.R
import com.lvtongka.app.base.BaseFragment
import com.lvtongka.app.common.AppUtils
import com.lvtongka.app.databinding.FragmentMyBinding
import com.lvtongka.app.fragment.common.DialogHelper
import com.lvtongka.app.fragment.my.adapter.MyGridAdapter
import com.lvtongka.app.http.common.WebConstants
import com.lvtongka.app.okpermission.PermissionLauncher
import com.lvtongka.app.ui.card.BindCardActivity
import com.lvtongka.app.ui.recharge.RechargeActivity
import com.lvtongka.app.ui.recharge.RechargeDelayActivity
import com.lvtongka.app.ui.setting.SettingActivity
import com.lvtongka.app.ui.splash.SplashActivity

/**
 * describe:
 *
 * @author:ZhangWei(张伟)
 * date:2024/11/3
 * time:9:45
 */
class MyFragment: BaseFragment<FragmentMyBinding, MyViewModel>() {
    companion object {
        const val TAG = "MyFragment_zw_test"
    }
    private var cardPckAdapter: MyGridAdapter? = null
    private var couponPckAdapter: MyGridAdapter? = null
    private var commonUsePckAdapter: MyGridAdapter? = null
    private var qrCode: String? = ""

    override fun initBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentMyBinding {
        return FragmentMyBinding.inflate(inflater, container, false)
    }

    override fun initViewModel(): MyViewModel {
        return ViewModelProvider(this)[MyViewModel::class.java]
    }

    override fun initEvent() {
        binding.tvMyGoRecharge.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            startActivityForResult(Intent(context, RechargeActivity::class.java), 11)
        }

        binding.gvWdkb.setOnItemClickListener { parent, view, position, id ->
            if (isFastClick()) {
                return@setOnItemClickListener
            }
            when(position) {
                0-> {
                    // 卡包
                    jumpWeb(WebConstants.LT_CARD_PACKAGE, true)
                }
                1-> {
                    // 绑卡
                    startActivity(Intent(context, BindCardActivity::class.java))
                }
                2-> {
                    // 查交易
                    jumpWeb(WebConstants.PAY_INFO_LIST)
                }
            }
        }

        // 我的券包
        binding.gvWdqb.setOnItemClickListener { parent, view, position, id ->
            if (isFastClick()) {
                return@setOnItemClickListener
            }
            when(position) {
                0 -> {
                    // 我的券包
                    jumpWeb(WebConstants.QUAN_PACKAE)
                }
                1 -> {
                    // 绑券
                    scan()
                }
                2 -> {
                    jumpWeb(WebConstants.COUPON_TRAN_LIST)
                }
                3 -> {
                    jumpWeb(WebConstants.QUAN_PACKAE)
                }
            }
        }

        // 我的工具
        binding.gvCygn.setOnItemClickListener { parent, view, position, id ->
            if (isFastClick()) {
                return@setOnItemClickListener
            }
            when (position) {
                0-> {
                    startActivity(Intent(context, RechargeDelayActivity::class.java))
                }
                1 -> {
                    jumpWeb(WebConstants.CARD_SEARCH_AMT)
                }
                2 -> {
                    jumpWeb(WebConstants.CARD_FLOW_B)
                }
                3 -> {
                    jumpWeb(WebConstants.CARD_LOSS)
                }
                4 -> {
                    jumpWeb(WebConstants.ADDRESS)
                }
                5 -> {
                    jumpWeb(WebConstants.HELP_CENTER)
                }
            }
        }
        binding.ivCustomerService.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            // 客服
            selectTelephone()
        }
        binding.ivSetting.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            // 设置
            startActivityForResult(Intent(context, SettingActivity::class.java), 1)
        }
        binding.tvWcdd.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_2, true)
        }
        binding.tvOrderCount.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_2, true)
        }
        binding.tvWcddB.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_2, true)
        }

        binding.tvDfk.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_1, true)
        }

        binding.tvObligation.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_1, true)
        }

        binding.tvDfkB.setOnClickListener{
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.ORDER_TYPE_1, true)
        }
        binding.tvMyQbye.setOnClickListener {
            if (isFastClick()) {
                return@setOnClickListener
            }
            jumpWeb(WebConstants.PAY_INFO_LIST)
        }
        viewModel.error.observe(this){
            hideLoading()
            showToast(it)
        }
        viewModel.listCardPck.observe(this) {
            cardPckAdapter = MyGridAdapter(context!!, it)
            binding.gvWdkb.adapter = cardPckAdapter
        }
        viewModel.listCouponPck.observe(this) {
            couponPckAdapter = MyGridAdapter(context!!, it)
            binding.gvWdqb.adapter = couponPckAdapter
        }
        viewModel.listCommonUse.observe(this) {
            commonUsePckAdapter = MyGridAdapter(context!!, it)
            binding.gvCygn.adapter = commonUsePckAdapter
        }
        viewModel.myInfo.observe(this) {
            hideLoading()
            binding.tvMyPhone.text = it.cell
            binding.tvMyQbye.text = AppUtils.convertFenToYuan(it.balance)
            binding.tvMyName.text = it.name
            // 更新数据
            if (TextUtils.equals(it.real_name_flag, "0")) {
                // 未实名
                binding.tvMyShiming.text = "未实名"
            } else {
                // 已实名
                binding.tvMyShiming.text = "已实名"
            }
        }
        viewModel.bindTicket.observe(this) {
            hideLoading()
            val bla = AppUtils.convertFenToYuan(it.balanceCent)
            DialogHelper.showBindQuanHintDialog(context!!, bla, it.remark) {
                showLoading("绑券中...")
                viewModel.scanCodeBindBp()
            }
        }
        viewModel.bindTicketBp.observe(this) {
            qrCode?.let { qr ->
                viewModel.scanCodeBindTicketB(qr)
            }
        }
        viewModel.bindTicketB.observe(this) {
            hideLoading()
            showToast("绑券成功")
        }
        viewModel.orderCountData.observe(this) {
            hideLoading()
            binding.tvOrderCount.text = it.successCount.toString()
            binding.tvObligation.text = it.pendCount.toString()
        }
    }

    override fun initData() {
        viewModel.initCardPck()
        viewModel.initCouponPck()
        viewModel.initCommonUse()
        showLoading()
        viewModel.getMyInfo()
        viewModel.getOrderCount()
    }

    fun refresh() {
        showLoading()
        viewModel.getMyInfo()
        viewModel.getOrderCount()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == 1 && resultCode == RESULT_OK) {
            startActivity(Intent(activity!!, SplashActivity::class.java))
            activity!!.finish()
            return
        }
        if (requestCode == 11 && resultCode == RESULT_OK) {
            showLoading()
            viewModel.getMyInfo()
            viewModel.getOrderCount()
        }
    }

    private fun selectTelephone() {
        DialogHelper.showPhoneHintDialog(context!!) {
            val intent = Intent(Intent.ACTION_DIAL)
            val data = Uri.parse("tel:" + "0519-85605725")
            intent.data = data
            startActivity(intent)
        }
    }

    private fun scan() {
        val listP = listOf(Permission.CAMERA)
        if (EasyPermissions.isGranted(activity!!, listP)) {
            startScan()
        } else {
            PermissionLauncher().with(this)
                .granted {
                    //所有权限都被授予了回调此处
                    startScan()
                }
                .denied {
                    //有权限被拒绝回调此处
                    //rejectPermissionList为被拒绝的权限列表
                    DialogHelper.showPermissionHintDialog(context!!, "相机服务未开启", "请在设置中为本应用开启相机服务以正常使用功能") {
                        PermissionLauncher.openAppDetailSettings(context!!)
                    }
                }
                .request(
                    Permission.CAMERA,
                    getString(R.string.okpermission_camera),
                    getString(R.string.okpermission_camera_rationale)
                )
        }
    }

    private fun startScan() {
        val config = MNScanConfig.Builder().isShowPhotoAlbum(false)
        MNScanManager.startScan(activity!!, config.builder()) { resultCode, data ->
            when (resultCode) {
                MNScanManager.RESULT_SUCCESS -> {
                    qrCode =
                        data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS)
                    qrCode?.let {
                        if (it.length != 26) {
                            showToast("请扫描正确的券码")
                            return@let
                        }
                        showLoading("查询中...")
                        viewModel.scanCodeBindTicket(it)
                    }
                }
                MNScanManager.RESULT_FAIL -> {
                    var resultError = data?.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR)
                    showToast(resultError)
                }
                MNScanManager.RESULT_CANCLE -> {
                    showToast("取消扫码")
                }
            }
        }
    }
}